package cc.rboot.repeat.validator;

import cc.rboot._core.helper.RequestHelper;
import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson.JSONObject;
import cc.rboot.repeat.core.IRepeatCommitValidator;
import cc.rboot.token.core.ITokenAware;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class LocalTokenRequestParamsRepeatCommitValidator implements IRepeatCommitValidator {

    private TimedCache<String, Boolean> timedCache = CacheUtil.newTimedCache(5000);

    @Resource
    ITokenAware tokenAware;

    @Override
    public boolean validator() {
        String token = tokenAware.token();
        String signature = token + "_" + JSONObject.toJSONString(RequestHelper.get().getParameterMap());
        signature = MD5.create().digestHex(signature);

        if (timedCache.containsKey(signature)) {
            return false; // 重复提交了
        }

        timedCache.put(signature, true);
        return true;
    }
}
